package com.dzj.fishingcommunity.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dzj.fishingcommunity.exception.GlobalExceptionHandler;
import com.dzj.fishingcommunity.mapper.OrderMapper;
import com.dzj.fishingcommunity.model.Order;
import com.dzj.fishingcommunity.model.Product;
import com.dzj.fishingcommunity.service.OrderService;
import com.dzj.fishingcommunity.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ProductService productService;

    @Override
    public boolean isStockEnough(Order order) {

        //准备sql语句，减去库存量
        String sql = "stock = stock - " + order.getQuantity();

        //获取商品id，使用乐观锁来获取商品信息
        return productService.lambdaUpdate().eq(Product::getId, order.getProductId())
                .gt(Product::getStock, 0)
                .setSql(sql)
                .update();
    }

    @Override
    public Boolean deleteOrder(Long id) {

        //1.根据id查询订单
        Order order = getById(id);
        if (order != null) {
            //2.恢复库存
            boolean stock = productService.lambdaUpdate().eq(Product::getId, order.getProductId())
                    .setSql("stock = stock + " + order.getQuantity())
                    .update();
            if (!stock) {
                new GlobalExceptionHandler().handleException(new RuntimeException("库存恢复失败"));
            }

            //3.删除订单
            return removeById(id);
        }

        return null;
    }
}